/*
 * (C) 2012	Sheng Yi
 * String to integer, and vice versa
 */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int atoi_u(char* str);

int main()
{
	char test1[] = "123456";
	assert(atoi_u(test1) == 123456);
	printf("string = %s, result = %d	PASS\n", test1, 123456);
	
	char test2[] = "-123456";
	assert(atoi_u(test2) == -123456);
	printf("string = %s, result = %d	PASS\n", test2, -123456);
	
	char test3[] = "   123456";
	assert(atoi_u(test3) == 123456);
	printf("string = %s, result = %d	PASS\n", test3, 123456);

	char test4[] = "asd1ad-2fg3h4-56";
	assert(atoi_u(test4) == 123456);
	printf("string = %s, result = %d	PASS\n", test4, 123456);

	char test5[] = "123sd4fad56";
	assert(atoi_u(test5) == 123456);
	printf("string = %s, result = %d	PASS\n", test5, 123456);

	char test6[] = "sdafg";
	assert(atoi_u(test6) == 0);
	printf("string = %s, result = %d	PASS\n", test6, 0);
	
	printf("Following is a integer to string(use sprintf):\n");
	char ch[100];
	sprintf(ch, "%d", 12345);
	printf("%d to a string %s\n", 12345, ch);
	return 0;
}


/*
 * Change a string to integer
 */
int atoi_u(char* str)
{
	char ch;
	int multi = 10;
	int res = 0;
	int sign = 0; // means positive integer
	if (!str)
	{
		printf("string is null.Aborting...\n");
		exit(1);
	}
	// check the first character: + or -?
	while (*str == ' ')	// ignore space in head
		str++;
	if (*str == '-')
		sign = 1;	
	while ((ch = *str++) != '\0')
	{
		if (ch >= '0' && ch <= '9')	// digital
			res = res * multi + (ch - '0');
	}

	if (sign)
		res = -res;
	return res;
}
